<?php

namespace lico\Tool\Cache;

class Redis
{

    protected $handler;
    protected $config = [
        'host'=>'127.0.0.1',
        'port'=>'6379',
        'prefix'=>'lico_',
        'password'=>'123123',
        'select'=>0,
        'timeout'=>0,
        'expire'=>60,
        'pconnnect'=>false,
    ];

    public function connect($config = [])
    {
        if (!extension_loaded('redis')) {
            die('not support: redis');
        }

        $this->config = array_merge($this->config, $config);

        $this->handler = new \Redis();
        if ($this->config['pconnnect']) {
            $this->handler->pconnect($this->config['host'], $this->config['port']);
        }else{
            $this->handler->connect($this->config['host'], $this->config['port'], $this->config['timeout']);
        }
        
        $this->handler->auth($this->config['password']);
        
        if (0 != intval($this->config['select'])) {
            $this->handler->select($this->config['select']);
        }

        return $this->handler;
    }

    public function set($key, $val, $expire = "")
    {
        $expire = $expire ?: $this->config['expire'];
        $this->handler->set($key, $val, $expire);
        return $this;
    }

    public function get($key)
    {
        return $this->handler->get($key);
    }

    public function exists($key)
    {
        return $this->handler->exists($key);
    }

}
